<template>
  <div>
    <div class="freight-wrapper">
      <h4 class="freight-title">运费模板</h4>
      <el-form ref="form" :model="form" label-width="150px" :rules="rules">
        <el-form-item label="模  板   名  称：" prop="templateName" >
          <el-input v-model="form.templateName" style="width: 370px"></el-input>
        </el-form-item>
        <el-form-item label="邮  费   类  型：" prop="freightWay">
          <el-radio-group v-model="form.freightWay">
            <el-radio :label="1">包邮</el-radio>
            <el-radio :label="0">自定义运费</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="快递计费方式：" prop="calculation" v-if="form.freightWay == 0 ">
          <el-radio-group v-model="form.calculation" @change="billingChange">
            <el-radio :label="0">按件数</el-radio>
            <el-radio :label="1">按重量</el-radio>
            <el-radio :label="2">按体积</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="快  递   类  型：" prop="shippingId" v-if="form.freightWay == 0">
          <el-radio-group v-model="form.shippingId" style="margin: 15px 0 10px 0;">
            <el-radio style="margin: 0 30px 10px 0;" v-for="item in shipperNameList" :key="item.label"
                      :label="item.label">{{item.value}}
            </el-radio>
          </el-radio-group>
          <div class="shipping-wrapper">
            <div class="shipping-top">
              <div>
                <span>默认运费</span>
                <el-input v-model="defaultFreightFree.firstWeight" style="width: 70px;" size="medium"
                          suffix-icon="el-icon-edit el-input__icon" type="number"></el-input>
                <span style="color: #909399;">{{unit01}}内</span>
                <el-input v-model="defaultFreightFree.firstWeightMoney" style="width: 70px;"
                          size="medium" suffix-icon="el-icon-edit el-input__icon" type="number"></el-input>
                <span style="color: #909399;">元，</span>
                <span>每增加</span>
                <el-input v-model="defaultFreightFree.continuedWeight" style="width: 70px;"
                          size="medium" suffix-icon="el-icon-edit el-input__icon" type="number"></el-input>
                <span style="color: #909399;">{{unit01}},</span>
                <span>增加运费</span>
                <el-input v-model="defaultFreightFree.continuedWeightMoney" style="width: 70px;"
                          size="medium" suffix-icon="el-icon-edit el-input__icon" type="number"></el-input>
                <span style="color: #909399;">元</span>
              </div>
            </div>
            <el-table
              :data="tableFreightCalculation"
              stripe
              style="width: 100%"
              :header-cell-class-name="headerClassName"
              @selection-change="handleSelectionChange">
              <el-table-column type="selection" v-if="isBatch" width="30">
              </el-table-column>
              <el-table-column label="运送到" width="220">
                <template slot-scope="scope">
                  <div style="display: flex;justify-content: space-between;align-items: center;">
                    <div style="font-size: 14px;color: #666">
                      <div style="width: auto;float: left;text-align: center;line-height: 40px;">{{scope.row.provinceId
                        ? filterProvincesName(scope.row.provinceId) : '未选择地区'}}
                      </div>
                      <div style="width: 120px;float: left;margin-left: 5px">
                        <el-cascader style="padding: 0" ref="cascader" :options="scope.row.cityList"
                                     :show-all-levels="false" v-model="scope.row.cityIds"
                                     @focus="getCity(scope.row.provinceId, scope.$index, 'freight')"
                                     :props="{ emitPath:false,multiple: true,checkStrictly: true }"
                                     clearable
                                     placeholder="全部城市">

                        </el-cascader>
                      </div>
                    </div>
                    <!-- <el-button size="mini" @click="selectProvince(scope.$index)">编辑</el-button> -->
                  </div>
                </template>
              </el-table-column>
              <el-table-column :label="'首'+unit02+'('+unit01+')'">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.firstWeight" size="medium" suffix-icon="el-icon-edit el-input__icon"
                            type="number"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="首费(元)">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.firstWeightMoney" size="medium" suffix-icon="el-icon-edit el-input__icon"
                            type="number"></el-input>
                </template>
              </el-table-column>
              <el-table-column :label="'续'+unit02+'('+unit01+')'">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.continuedWeight" size="medium" suffix-icon="el-icon-edit el-input__icon"
                            type="number"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="续费(元)">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.continuedWeightMoney" size="medium"
                            suffix-icon="el-icon-edit el-input__icon" type="number"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button @click="deleteFreight(scope.$index, scope.row.key)" size="mini">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="shipping-batch" v-show="isBatch">
              <el-button size="mini" @click="addSelectFreight">批量设置</el-button>
              <el-button size="mini" @click="deleteSelectFreight">批量删除</el-button>
            </div>
            <div class="shipping-bottom">
              <el-button size="mini" @click="addFreight" type="primary">为指定地区城市设置运费</el-button>
              <!-- <el-button size="mini" @click="doBatch">{{isBatch ? '取消批量操作' : '批量操作'}}</el-button> -->
            </div>
          </div>
        </el-form-item>
        <el-form-item label="指定条件包邮：" v-if="form.freightWay == 0 ">
          <el-switch
            v-model="switchValue">
          </el-switch>
          <div style="border:1px solid #ebeef5;" v-if="switchValue">
            <el-table
              :data="tableDataFreightFree"
              stripe
              :header-cell-class-name="headerClassName">
              <el-table-column label="选中地区" width="200">
                <template slot-scope="scope">
                  <div style="display: flex;justify-content: space-between;align-items: center;">
                    <div style="font-size: 14px;color: #666">
                      <div style="width: auto;float: left;text-align: center;line-height: 40px;">{{scope.row.provinceId
                        ? filterProvincesName(scope.row.provinceId) : '未选择地区'}}
                      </div>
                      <div style="width: 120px;float: left;margin-left: 5px">
                        <el-cascader style="padding: 0" ref="cascader" :options="scope.row.cityList"
                                     :show-all-levels="false" v-model="scope.row.cityIds"
                                     @focus="getCity(scope.row.provinceId, scope.$index, 'freight')"
                                     :props="{ emitPath:false,multiple: true,checkStrictly: true }"
                                     clearable
                                     placeholder="全部城市">

                        </el-cascader>
                      </div>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="设置包邮条件" width="350">
                <template slot-scope="scope">
<!--                  <el-select v-model="scope.row.conditionType" size="small" placeholder="请选择">-->
<!--                    <el-option-->
<!--                      v-for="item in options"-->
<!--                      :key="item.value"-->
<!--                      :label="item.label"-->
<!--                      :value="item.value">-->
<!--                    </el-option>-->
<!--                  </el-select>-->
                  <div v-if="scope.row.conditionType && scope.row.conditionType.length != 2">
                    <span>在</span>
                    <el-input v-model="scope.row.conditionValue01" style="width: 120px;margin-top: 5px;"
                              size="medium" suffix-icon="el-icon-edit el-input__icon"
                              type="number"></el-input>
                    <span>{{scope.row.conditionType | filterText}}内包邮</span>
                  </div>
                  <div v-if="scope.row.conditionType && scope.row.conditionType.length == 2">
                    <span>在</span>
                    <el-input v-model="scope.row.conditionValue02" style="width: 120px;margin-top: 5px;"
                              size="mini"></el-input>
                    <span>{{scope.row.conditionType[1] | filterText}}内,</span>
                    <el-input v-model="scope.row.conditionValue03" style="width: 120px;margin-top: 5px;"
                              size="medium" suffix-icon="el-icon-edit el-input__icon"
                              type="number"></el-input>
                    <span>元以上包邮</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button @click="deleteFreight02(scope.$index, scope.row.key)" size="mini">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="shipping-bottom">
              <el-button @click="addFreight02()" type="primary" size="mini">增加指定条件包邮</el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <!-- <el-button @click="update" >修改并返回</el-button> -->
          <el-button @click="submit('form')">保存并返回</el-button>
          <el-button @click="handleCancel">返回</el-button>
        </el-form-item>
      </el-form>
      <el-dialog
        title="省份"
        :visible.sync="dialogVisible"
        width="40%">
        <el-checkbox-group
          v-model="freightCalculationCheckedList">
          <el-checkbox v-for="item in provinceList" :label="item.value" :key="item.value">{{item.label}}</el-checkbox>
        </el-checkbox-group>
        <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="handleFreightCalculationProvinces">确 定</el-button>
                </span>
      </el-dialog>
      <el-dialog
        title="省份"
        :visible.sync="dialogVisible02"
        width="40%">
        <el-checkbox-group
          v-model="freightFreeCheckedList">
          <el-checkbox v-for="item in provinceList" :label="item.value" :key="item.value">{{item.label}}</el-checkbox>
        </el-checkbox-group>
        <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible02 = false">取 消</el-button>
                    <el-button type="primary" @click="handleFreightFreeProvinces">确 定</el-button>
                </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  import {
    getObj as getTempalteInfo,
    addObj as saveFreightTemplate
  } from '@/api/supplier/freightTemplate'
  import { fetchList as areaList } from '@/api/supplier/area'
  import { fetchList as shipperList } from '@/api/order/shippingInfo'
  import { filterAddressData } from '@/util/util'
  import { globalNotify, globalWarning } from '@/util/notifyUtils'  //弹窗
  import { cloneObject } from '../../../util/casUtils'

  export default {
    name: 'freightAdd',
    data() {
      return {
        areaQuery: {
          page: 1,
          limit: 200,
          areaName: undefined,
          parentId: undefined,
          grade: undefined //0-大区 1-省 2-市 3-县 4-乡
        },
        shipperQuery: {
          page: 1,
          limit: 200
        },
        form: {
          id: undefined,
          templateName: undefined,
          isFreight: '0',
          freightWay: '0',
          calculation: '0',
          isPost: 0,
          shippingId: undefined
        },
        freightCalculationList: [],
        tableFreightCalculation: [],
        isBatch: false,
        selectTableData: [],
        unit01: '',
        unit02: '',
        switchValue: false, //是否指定条件包邮
        switchValue02: false,
        freightFreeList: [],
        tableDataFreightFree: [],
        options: [{
          value: '0',
          label: '件'
        }
        ],
        options01: [{
          value: '0',
          label: '件'
        }
        ],
        rules: {
          templateName: [
            { required: true, message: '请输入活动名称', trigger: 'blur' }
          ],
          freightWay: [
            { required: true, message: '请选择包邮方式', trigger: 'change' }
          ],
          isFreight: [
            { required: true, message: '请选择是否包邮', trigger: 'change' }
          ],
          calculation: [
            { required: true, message: '请选择计费方式', trigger: 'change' }
          ]
        },
        provinceList: [],
        dialogVisible: false,
        dialogVisible02: false,
        dialogVisible03: false,
        freightCalculationCheckedList: [],
        freightFreeCheckedList: [],
        checkedList03: [],
        tempIndex: 0,
        shipperNameList: [],
        condition01: '',
        condition02: '',
        defaultFreight: [],
        defaultFreightFree: {
          firstWeight: 0,
          firstWeightMoney: 0,
          continuedWeight: 0,
          continuedWeightMoney: 0,
          specified: 0,
          templateId: undefined,
          provinceId: undefined
        },
        freightCalculationFrom: {
          key: (new Date()).valueOf(),
          provinceId: undefined,
          cityIds: [],
          firstWeight: 0,
          firstWeightMoney: 0,
          continuedWeight: 0,
          continuedWeightMoney: 0,
          specified: 1
        },
        freightFreeFrom: {
          key: (new Date()).valueOf(),
          provinceId: undefined,
          cityIds: [],
          conditionValue: [],
          conditionType: undefined,
          conditionValue01: 0,
          conditionValue02: 0,
          conditionValue03: 0
        },
        id: '',
        cityList: []
      }
    },
    created() {
      this.id = this.$route.query.templateId
      this.getProvince(this.id)
      this.getShipper()
      this.billingChange(this.form.calculation)
    },
    methods: {
      handleCancel() {
        this.$store.commit("DEL_CURRENT_TAG", null);
        this.$router.push({path: '/supplier/freightTemplate'})
      },
      async getProvince(id) {
        this.areaQuery.grade = 1
        const res = await areaList(this.areaQuery)
        this.provinceList = filterAddressData(res.data.data.records, true)
        if (id) {
          this.getTemplateById(this.id)
        }
      },
      async getCity(value, index, type) {
        let cityList = []
        this.areaQuery.grade = 2
        this.areaQuery.parentId = value
        const res = await areaList(this.areaQuery)
        cityList = filterAddressData(res.data.data.records, true)
        // alert(JSON.stringify(cityList))
        if (type == 'freight') {
          this.freightCalculationList.forEach((item, index02) => {
            if (item.provinceId == value) { //省份id相等时
              item.cityList = cityList
            }
          })
          this.freightCalculationList = Object.assign([], this.freightCalculationList)
          this.freightCalculationDeffi(this.freightCalculationList)
        } else if (type == 'free') {
          this.freightFreeList.forEach((item, index02) => {
            if (item.provinceId == value) {
              item.cityList = cityList
            }
          })
          this.freightFreeList = Object.assign([], this.freightFreeList)
          this.freightFreeDeffi(this.freightFreeList)
        }
      },
      headerClassName({ row, rowIndex }) {
        return 'header-class-name'
      },
      addFreight() {
        this.dialogVisible = true
        this.freightCalculationCheckedList = []
        this.freightCalculationList.forEach(item => {
          this.freightCalculationCheckedList.push(item.provinceId)
        })
      },
      addFreight02() {
        this.dialogVisible02 = true
        this.freightFreeCheckedList = []
        this.freightFreeList.forEach(item => {
          this.freightFreeCheckedList.push(item.provinceId)
        })
      },
      async deleteFreight(index, key) {
        let delIndex = this.freightCalculationList.findIndex(item => item.key == key)
        this.freightCalculationList.splice(delIndex, 1)
        this.freightCalculationDeffi(this.freightCalculationList)
      },
      async deleteFreight02(index, key) {
        let delIndex = this.freightFreeList.findIndex(item => item.key == key)
        this.freightFreeList.splice(delIndex, 1)
        this.freightFreeDeffi(this.freightFreeList)
      },
      handleSelectionChange(val) {
//              console.log(val, 'val')
        this.selectTableData = val
      },
      freightCalculationDeffi(dataList) { //把tableData数据分到express和logistics
        this.tableFreightCalculation = []
        dataList.forEach(item => {
          this.tableFreightCalculation.push(item)
        })
        this.tableFreightCalculation.forEach((item, index) => {
          this.$set(item, 'cityList', item.cityList)
        })
      },
      freightFreeDeffi(dataList) {
        this.tableDataFreightFree = []
        dataList.forEach(item => {
          this.tableDataFreightFree.push(item)
        })
        this.tableDataFreightFree.forEach((item, index) => {
          this.$set(item, 'cityList', item.cityList)
        })
      },
      deleteSelectFreight() { //批量删除
      },
      addSelectFreight() {  //批量增加
      },
      handleFreightCalculationProvinces() {
        let temArr = []
        let isHas = false
        let i = 0

        this.freightCalculationCheckedList.forEach(item => {
          this.freightCalculationList.forEach((item02) => {
            if (item == item02.provinceId) { //省份Id相同，并且运送方式相同时才不需要push
              isHas = true
            }
          })

          if (!isHas) {
            i++
            this.freightCalculationFrom.key = (new Date()).valueOf() + i
            this.freightCalculationFrom.provinceId = item
            temArr.push(this.freightCalculationFrom)
          }

          isHas = false
        })

        if (temArr.length != 0) {
          this.freightCalculationList = this.freightCalculationList.concat(temArr)
        }
        this.freightCalculationList = Object.assign([], this.freightCalculationList)
        this.freightCalculationDeffi(this.freightCalculationList)
        this.dialogVisible = false
      },
      handleFreightFreeProvinces() {
        let temArr = []
        let isHas = false
        let i = 0
        this.freightFreeCheckedList.forEach(item => {
          this.freightFreeList.forEach((item02) => {
            if (item == item02.provinceId) {
              isHas = true
            }
          })

          if (!isHas) {
            i++
            this.freightFreeFrom.key = (new Date()).valueOf() + i
            this.freightFreeFrom.provinceId = item
            this.freightFreeFrom.conditionType = this.form.calculation.toString()

            temArr.push(this.freightFreeFrom)
          }

          isHas = false
        })
        if (temArr.length != 0) {
          this.freightFreeList = this.freightFreeList.concat(temArr)
        }
        this.freightFreeList = Object.assign([], this.freightFreeList)
        this.freightFreeDeffi(this.freightFreeList)
        this.dialogVisible02 = false
      },
      async getShipper() {
        const res = await shipperList(this.shipperQuery)
        this.shipperNameList = []
        res.data.data.records.forEach((item, index) => {
          this.shipperNameList.push({
            label: item.id,
            value: item.shipName
          })
        })
      },
      submit(formName) {
        this.$refs[formName].validate(async(valid) => {
//                  console.log(this.$refs[formName], 'this.$refs[formName]')
          if (valid) {
            this.defaultFreightFree.provinceId = 0
            this.defaultFreightFree.templateId = this.form.id
            let delIndex = this.freightCalculationList.findIndex(item => item.specified === 0)
            if (delIndex > -1) {
              this.freightCalculationList.splice(delIndex, 1)
            }

            const tempFreightCalculationList = this.freightCalculationList
            tempFreightCalculationList.push(this.defaultFreightFree)

            if (this.freightFreeList.length > 0) {
              this.freightFreeList.forEach(item => {

                if (item.conditionType.length == 1) {
                  if (item.conditionValue01 == undefined) {
                    item.conditionValue01 = 0
                  }
                  item.conditionValue = Number(item.conditionType[0]) == 3 ? [item.conditionValue01] : [item.conditionValue01]
                }
                if (item.conditionType.length == 2) {
                  if (item.conditionValue02 == undefined) {
                    item.conditionValue02 = 0
                  }
                  if (item.conditionValue03 == undefined) {
                    item.conditionValue03 = 0
                  }
                  item.conditionValue = [item.conditionValue02, item.conditionValue03]
                }
              })
            }
            let postData = {
              freightTemplate: this.form,
              freightFreeList: this.freightFreeList,
              freightCalculationList: tempFreightCalculationList
            }
            const response = await saveFreightTemplate(postData)
            if (response.data.code == 0) {
              //跳转
              this.handleCancel()
            }
            globalNotify(this, response)
          } else {
            return false
          }
        })
      },
      cancelSave() {
        this.$router.push({ path: '/freight/freightIndex' })
      },
      async getTemplateById(id) {  //通过id获取运费模板信息
        const res = await getTempalteInfo(id)
//              console.log(res, '模板信息')

        let freightTemplate = res.data.data.freightTemplate
        let freightCalculationList = res.data.data.freightCalculationList
        let freightFreeList = res.data.data.freightFreeList
        console.log('freightTemplate', freightTemplate)

        console.log('freightFreeList', freightFreeList)
        this.form = Object.assign({}, freightTemplate)

        //通过chargType筛选this.options
        this.billingChange(this.form.calculation)

        //删除运费配置 默认运费，显示
        let index = 0
        freightCalculationList.forEach((item, index01) => {
          if (!item.specified) {
            index = index01
            this.defaultFreightFree = cloneObject(item)
          }
        })

        freightCalculationList.splice(index, 1)

        //请求对应 运费设置的省份下 城市数据
        let i = 0
        freightCalculationList.forEach(item02 => {
          i++
          this.areaQuery.grade = 2
          this.areaQuery.parentId = item02.provinceId
          this.getAreaDat(this.areaQuery, item02)
        })

        this.freightCalculationList = Object.assign([], freightCalculationList)
        ////把tableData数据分到快递、物流 里边
        this.freightCalculationDeffi(this.freightCalculationList)
        console.log('freightCalculationList', freightCalculationList)

        if (freightFreeList.length > 0) {
          this.switchValue = true
          freightFreeList.forEach(item => {
            item.conditionType = String(item.conditionType)
            if (item.conditionValue.length == 1) {
              if (Number(item.conditionValue[0]) == 3) {
                item.conditionValue01 = item.conditionValue[0]
              } else {
                item.conditionValue01 = Number(item.conditionValue[0])
              }
            }
            if (item.conditionValue.length == 2) {
              item.conditionValue02 = item.conditionValue[0]
              item.conditionValue03 = item.conditionValue[1]
            }
          })

          this.freightFreeList = Object.assign([], freightFreeList)
          this.freightFreeList.forEach(item03 => {
            i++
            this.areaQuery.grade = 2
            this.areaQuery.parentId = item03.provinceId
            this.getAreaDat(this.areaQuery, item03)
          })

          this.freightCalculationList = Object.assign([], freightCalculationList)

          this.freightFreeDeffi(this.freightFreeList)
        }
      },
      async getAreaDat(params, item) {
        const res = await areaList(params)
        item.cityList = filterAddressData(res.data.data.records, true)
        item.key = (new Date()).valueOf()
      },
      resetDeliveryData(val, arr) {
        arr.forEach(item => {
          switch (Number(val)) {
            case 0:
              item.conditionType = '0'
              break
            case 1:
              item.conditionType = '1'
              break
            case 2:
              item.conditionType = '2'
              break
          }

          item.conditionValue01 = 0
          item.conditionValue02 = 0
          item.conditionValue03 = 0

          item.min = undefined
          item.max = undefined
          item.money = undefined

        })
      },
      isPostChange(value) {
        if (value == 0) {
          this.form.freightWay = '1'
        } else {
          this.form.freightWay = '0'
        }
      },
      billingChange(val) {
        this.resetDeliveryData(val, this.tableDataFreightFree)

        switch (Number(val)) {
          case 0:
            this.unit01 = '件'
            this.unit02 = '件'
            this.options = [{
              value: '0',
              label: '件'
            }
            ]

            this.options01 = [{
              value: '0',
              label: '件'
            }
            ]
            break
          case 1:
            this.options = [{
              value: '1',
              label: '重量(kg)'
            }]

            this.options01 = [{
              value: '1',
              label: '重量(kg)'
            }]

            this.unit01 = 'kg'
            this.unit02 = '重量'
            break
          case 2:
            this.options = [{
              value: '2',
              label: '体积(m³)'
            }]
            this.options01 = [{
              value: '2',
              label: '体积(m³)'
            }]

            this.unit01 = 'm³'
            this.unit02 = '体积'
            break
        }
      },
      filterProvincesName(val) {
        let tempLabel = ''
        this.provinceList.forEach(item => {
          if (item.value == val) {
            tempLabel = item.label
          }
        })
        return tempLabel
      }
    },
    filters: {
      filterText(val) {
        let stateMap = {
          '0': '件',
          '1': 'kg',
          '2': 'm³',
          '3': '元'
        }
        return stateMap[val]
      }
    }
  }
</script>
<style lang="scss">
  .freight-wrapper {
    width: 70%;
    margin: 0 auto;

    .freight-title {
      margin-bottom: 10px;
    }

    .shipping-wrapper {
      border: 1px solid #ebeef5;

      .shipping-top {
        padding: 5px 10px;
        background-color: #e9f2ff;
      }

      .shipping-batch {
        padding: 0 0 10px 10px;
      }
    }

    .shipping-bottom {
      padding: 0 10px;
    }

    .header-class-name {
      background-color: #fafafa;
    }
  }
</style>

